package com.qf.blog.interceptor;

import com.qf.blog.commons.constant.BlogConstants;
import com.qf.blog.commons.utils.CookieUtil;
import com.qf.blog.commons.utils.UserThreadLocal;
import com.qf.blog.dto.TokenDto;
import com.qf.blog.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User: key
 * ClassName:UserInterceptor
 * Date: 2023/5/26
 * Time: 11:48
 * description:
 */
// 拦截器：在调用Controller之前被执行
@Component // 自定义拦截器放入到IOC容器中
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private UserTokenService userTokenService;

    // 在Controller之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuid = CookieUtil.getValue(BlogConstants.LOGIN_COOKIE_KEY);
        if (!ObjectUtils.isEmpty(uuid)) {
            TokenDto tokenDto = userTokenService.getUser(uuid);
            if (tokenDto != null) {
                UserThreadLocal.set(tokenDto);
            }
        }
        return true; // 直接放行
    }

    // 在Controller之后调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TokenDto tokenDto = UserThreadLocal.get();
        UserThreadLocal.remove();
        if (modelAndView != null && tokenDto != null) {
            modelAndView.addObject("loginUser", tokenDto);
        }
    }

    // 在视图渲染完成之后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
